<%-- 
    Document   : role
    Created on : 2018-11-1, 12:26:45
    Author     : yaohk
--%>
<%@page import="com.cmti.commons.web.AuthenticationFilter"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%
//    pageContext.setAttribute("contextPath", request.getContextPath());
    pageContext.setAttribute("loginUser", session.getAttribute(AuthenticationFilter.AUTH_INFO));
%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>角色权限管理</title>
        <%@include file="/WEB-INF/jspf/layui/top_layui.jspf" %>
<!--        <script type="text/javascript" src="${contextPath}/resources/js/jquery.form.js"></script>-->
        <style type="text/css">
            .title{
                background: #fafafa; border-bottom: 1px solid #ddd; padding-left: 5px; height: 30px;line-height: 30px; font-size: 14px; font-weight: 700;color: #999;
            }
        </style>
    </head>
    <body>
        <script type="text/javascript">
            $("body").mask({
                maskMsg: '<div class="loading_text"><img src="${contextPath}/resources/images/loading_2.gif"/><span>正在初始化，请稍后...</span></div>',
                opacity: 1
            });
            $(function () {
                $("body").mask('hide');
            });
        </script>
        <!--搜素框-->
        <!--<div class="layui-container" style="margin-top: 10px;">-->
        <div class="layui-row layui-col-space10" style="margin: 6px 0px 0px 5px;">
            <div class="layui-col-md2">
                <input type="text" id="role_name" name="role_name" placeholder="请输入角色名" class="layui-input"/>
                <a class="" id="search_role_name" style="display: inline-block;width: 20px;height: 36px;line-height: 36px; position: absolute;top:6px; right:6px;"><i class="layui-icon layui-icon-search"></i></a>
            </div>
            <div class="layui-col-md2">
                <div class="layui-form" lay-filter="*">
                    <select name="role_status" id="role_status" >
                        <option value="">请选择状态</option>
                        <option value="0">激活</option>
                        <option value="1">冻结</option>
                    </select>
                </div>
            </div>
            <div class="layui-col-md3">
                <button class="layui-btn layui-btn-sm" id="reset" style="height: 36px;"><i class="layui-icon layui-icon-refresh"></i>&nbsp;重&nbsp;&nbsp;置</button>
                <shiro:hasPermission name="role:add:*">
                    <button class="layui-btn layui-btn-sm" lay-filter="formDemo" id="add_role" style="height: 36px;"><i class="layui-icon">&#xe608;</i>&nbsp;添加角色</button>
                </shiro:hasPermission>
            </div>
        </div>
        <!--</div>-->

        <!--数据表格-->
        <table id="role" lay-filter="role" class=""></table>

        <!--增加/修改角色  -->
        <form class="layui-form" id="role_details" lay-filter="details" style="display: none; margin: 5px; min-width: 380px; min-height: 380px; border: 1px solid #ddd;">
            <div class="title" style=""><i class="layui-icon layui-icon-tabs" style="color: #0081C2;"></i> &nbsp;基本信息</div>
            <div style="margin: 5px 0px 0px 10px; min-height: 125px;">
                <input type='hidden' name='id' id="roleId"/>
                <div class="layui-form-item">
                    <div class="layui-inline" >
                        <label class="layui-form-label" style="padding: 9px 5px; width: auto;">角色名称</label>
                        <div class="layui-input-inline">
                            <input type="text" id="name" name="name" placeholder="请输入角色名称" lay-verify="required" autocomplete="off" class="layui-input" />
                        </div>
                    </div>
                    <div class="layui-inline">
                        <div class="layui-input-inline" style="width: 65px; margin-bottom: 15px; height: 24px;">
                            <input type="checkbox" name="rStatus" id="rStatus" lay-skin="switch" lay-filter="roleStatus" lay-text="激活|冻结" checked />
                            <input type="hidden" name="status" id="status" value="0"/>
                            <!--<input type='hidden' name='status' id="status"/>-->
                        </div>
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label" style="padding: 9px 5px; width: auto;">角色描述</label>
                    <div class="layui-input-block" style="margin: 0px;">
                        <textarea class="layui-textarea" id="remark" name="remark" style="width:270px; min-height: 50px; height: 50px;"></textarea>
                    </div>
                </div>
            </div>

            <div class="title" style="border-top: 1px solid #ddd;">
                <p><i class="layui-icon layui-icon-senior" style="color: #0081C2;"></i>&nbsp;权限设置</p>
            </div>
            <div style="min-height: 180px;">
                <div class="layui-form-item">
                    <div class="layui-input-block" style="margin-left: 20px;">
                        <input type="hidden" id="right_Ids" name="rightIds"/>
                        <div id="LAY-auth-tree-index"></div>
                    </div>
                </div>
            </div>
            <button type="button" class="layui-btn layui-btn-sm" lay-submit lay_filter="*" id="add" style="display: none;">添加</button>
        </form>


        <script type="text/javascript">
            layui.config({
                base: '${contextPath}/layui/'
            }).extend({
                authtree: 'authtree'
            }).use(['table', 'layer', 'form', 'authtree', 'element'], function () {
                var table = layui.table;
                var layer = layui.layer;
                var form = layui.form;
                var authtree = layui.authtree;
                var element = layui.element;
                var openContent;
                var tableIns = table.render({
                    elem: '#role',
//                    height: 490,
                    url: '${contextPath}/role/list/dataL.json', //数据接口,
                    page: {//支持传入 laypage 组件的所有参数（某些参数除外，如：jump/elem） - 详见文档
                        layout: ['limit', 'count', 'prev', 'page', 'next', 'skip', 'refresh'], //自定义分页布局
                        limits: [5, 10, 20, 30, 50],
                        groups: 5,
                        first: false, //不显示首页和尾页
                        last: false
                    },
                    //                    page:true,
                    text: {none: '暂无相关数据！'}, //自定义文本，如空数据时的异常提示等。
                    even: true, //隔行背景
//                    size: 'sm',
                    autoSort: false, //禁用前端自动排序。注意：该参数为 layui 2.4.4 新增
                    cols: [[//
                            {type: 'numbers', fixed: 'left'},
                            {field: 'open', title: '操作', fixed: 'left', align: 'center', width: 150,
                                templet: function (d) {
                                    openContent = '';
            <shiro:hasPermission name="role:detail:*">
                                    openContent += '<a href="#" lay-event="showDetails" title="查看详情"><i class="layui-icon layui-icon-table" ></i></a>&nbsp;&nbsp;&nbsp;&nbsp;';
            </shiro:hasPermission>
            <shiro:hasPermission name="role:modify:*">
                                    openContent += '<a href="#" lay-event="edit" title="编辑"><i class="layui-icon layui-icon-edit"></i></a>&nbsp;&nbsp;&nbsp;&nbsp;';
            </shiro:hasPermission>
            <shiro:hasPermission name="role:delete:*">
                                    openContent += '<a href="#" lay-event="delete" title="删除"><i class="layui-icon layui-icon-delete"></i></a>&nbsp;&nbsp;&nbsp;&nbsp;';
            </shiro:hasPermission>
            <shiro:hasPermission name="role:modify:*">
                                    if (d.status === 0) {
                                        openContent += '<a href="#" lay-event="toLock" title="冻结"><i class="layui-icon layui-icon-password"></i></a>';
                                    } else {
                                        openContent += '<a href="#" lay-event="toLock" title="激活"><i class="layui-icon layui-icon-auz"></i></a>';
                                    }
            </shiro:hasPermission>
                                    return openContent;
                                },
                                toolbar: openContent},
                            {field: 'name', title: '角色名称', sort: true, align: 'center'},
                            {field: 'remark', title: '角色描述', align: 'center'},
                            {field: 'status', title: '状态', width: 100, sort: true, align: 'center',
                                templet: function (d) {
                                    if (d.status === 0) {
                                        return '激活';
                                    } else {
                                        return '<span style="color: #f00;">冻结</span>';
                                    }
                                }
                            }
                        ]]
                });
                table.on('tool(role)', function (obj) {
                    if (obj.event === 'showDetails') {
                        showDetails(obj.data);
                    } else if (obj.event === 'edit') {
                        edit(obj.data);
                    } else if (obj.event === 'delete') {
                        Delete(obj.data);
                    } else if (obj.event === 'toLock') {
                        toLock(obj.data);
                    }
                });
                //监听行双击事件
                table.on('rowDouble(role)', function (obj) {
                    showDetails(obj.data);
                });
                //表单验证
                var verify = false;
                form.verify({
                    required: function (value) {
                        if (!/[^\s]+/.test(value)) {
                            verify = false;
                            return '必填项不能为空';
                        } else {
                            verify = true;
                        }
                    }
                });
                //                查看详情
                function showDetails(data) {
                    $.ajax({
                        url: "${contextPath}/role/detail/ui.json?",
                        success: function () {
                            authority(data.id); //获取其权限
                            form.val('details', {//表单赋值
                                'name': data.name,
                                'remark': data.remark,
                                'status': status == 0 ? true : false
                            });
                            $('#name').attr('disabled', 'disabled');
                            $('#rStatus').attr('disabled', 'disabled');
                            $('#remark').attr('disabled', 'disabled');
                            layer.open({
                                title: '查看角色信息',
                                area: ['416px', '500px'],
                                scrollbar: false,
                                type: 1,
                                maxmin: true,
                                content: $("#role_details"),
                                btn: '取消'
                            });
                        }
                    });
                }
                //编辑
                function edit(data) {
                    $.ajax({
                        url: "${contextPath}/role/modify/ui.json?roleId=" + data.id,
                        success: function () {
                            authority(data.id);
                            form.val('details', {//表单赋值
                                'id': data.id,
                                'name': data.name,
                                'remark': data.remark,
                                'status': data.status,
                                'rStatus': data.status == 0 ? true : false
                            });
                            $('#name').removeAttr('disabled'); //解除禁用编辑
                            $('#rStatus').removeAttr('disabled');
                            $('#remark').removeAttr('disabled');
                            layer.open({
                                title: '修改角色信息',
                                area: ['416px', '500px'],
                                scrollbar: false,
                                type: 1,
                                maxmin: true,
                                content: $("#role_details"),
                                btn: ['保存', '取消'],
                                yes: function () {
                                    $('#add').click();
                                    if (verify)
                                        addOrUpdate("${contextPath}/role/modify/action.json");
                                }
                            });
                        }
                    });
                }
                //添加角色
                $('#add_role').click(function () {
                    $.ajax({
                        url: "${contextPath}/role/add/ui.json",
                        success: function () {
                            $('#name').val('');
                            $('#remark').val('');
                            $('#name').removeAttr('disabled'); //取消禁用
                            $('#status').removeAttr('disabled');
                            $('#remark').removeAttr('disabled');
                            authority(0);
                            layer.open({
                                title: '添加角色信息',
                                area: ['416px', '500px'],
                                scrollbar: false,
                                type: 1,
                                maxmin: true,
                                content: $("#role_details"),
                                btn: ['添加', '取消'],
                                yes: function () {
                                    $('#add').click();
                                    if (verify)
                                        addOrUpdate('${contextPath}/role/add/action.json');
                                }
                            });
                        }
                    });
                });
                $('#close').click(function () {
                    layer.closeAll();
                });
                //                删除用户
                function Delete(data) {
                    $.ajax({
                        url: "${contextPath}/role/delete/ui.json",
                        success: function () {
                            layer.open({
                                title: '友情提示',
                                content: '您确定要删除角色名为【' + data.name + '】的角色吗？',
                                icon: 3,
                                btn: ['确定', '取消'],
                                yes: function () {
                                    $.ajax({
                                        type: "post",
                                        url: "${contextPath}/role/delete.json?roleId=" + data.id,
                                        success: function (da) {
                                            var str = '删除成功！', msg = '';
                                            if (!da.result) {
                                                str = '删除失败！';
                                                msg = da.msg;
                                            }
                                            layer.close(layer.index);
                                            layer.msg(str + msg);
                                            tableIns.reload();
                                        }
                                    });
                                }
                            });
                        }
                    });
                }

                var ids = null;
                authtree.on('change(lay-check-auth)', function (data) {
//                    console.log('监听 authtree 触发事件数据', data);
                    // 获取所有已选中节点
                    var checked = authtree.getChecked('#LAY-auth-tree-index');
//                        console.log('checked', checked);
                    ids = checked.join(); //数组转字符串
                    $('#right_Ids').val(ids);
//                    console.log($('#right_Ids').val());
                });
                function addOrUpdate(url) {
//                    if ($('#name').val() == '') {
//                        layer.tips('请输入用户名！', '#name');
//                        return false;
//                    }
//                    if (ids == null || ids == '') {
//                        layer.msg('请选择权限！');
//                        return false;
//                    }
                    var upOptions = {//表单提交前的配置（jquery-form）
                        url: url,
                        type: "post",
                        dataType: 'json',
                        beforeSend: function (xhr) {

                        },
                        success: function (data) {
                            if (data.result) {
                                layer.close(layer.index);
                                layer.msg('保存成功');
                                tableIns.reload(); //表单重载
                            } else {
                                layer.msg('保存失败<br/>' + data.msg);
                            }
                        }
                    };
                    $('#role_details').ajaxSubmit(upOptions);
                }

//                监听开关  
                form.on('switch(roleStatus)', function (data) {
                    $('#status').val(data.elem.checked ? 0 : 1);
                });
//                冻结/激活角色
                function toLock(data) {
                    $.ajax({
                        url: "${contextPath}/role/modify/ui.json?roleId=" + data.id,
                        success: function () {
                            var str = '激活', status = 0;
                            if (data.status == '0') {
                                str = '冻结';
                                status = 1;
                            }
                            layer.open({
                                title: '友情提示',
                                content: '您确定要' + str + '角色名为【' + data.name + '】的角色吗？',
                                icon: 3,
                                btn: ['确定', '取消'],
                                yes: function () {
                                    $.ajax({
                                        type: "post",
                                        url: "${contextPath}/role/modify/lockRole.json?roleId=" + data.id + "&status=" + status,
                                        success: function () {
                                            layer.close(layer.index);
                                            layer.msg(str + '成功', {icon: 6});
                                            tableIns.reload();
                                        },
                                    });
                                }
                            });
                        }
                    });
                }

                //监听排序事件
                table.on('sort(role)', function (obj) {
                    tableIns.reload({
                        initSort: obj, //记录初始排序，如果不设的话，将无法标记表头的排序状态。
                        where: {//请求参数
                            name: $('#role_name').val(),
                            status: $('#role_status').val(),
                            sort: obj.field, //排序字段
                            order: obj.type //排序方式 
                        }
                    });
                });
                function authority(id) {
                    $.ajax({
                        url: '${contextPath}/role/list/authtree.json?loginUserId=' + ${loginUser.id} + '&roleId=' + id,
                        type: 'post',
                        success: function (data) {
                            var checked = new Array();
                            for (var i = 0; i < data.checkedId.length; i++) {
                                checked[i] = data.checkedId[i].id;
                            }
                            ids = checked.join();
                            $('#right_Ids').val(ids);
                            var trees = authtree.listConvert(data.list, {
                                //                            支持 primaryKey(主键 默认id) parentKey(父级id对应键 默认pid)nameKey(节点标题对应的key 默认name)  valueKey(节点值对应的key 默认id) checkedKey(节点是否选中的字段 默认checked,传入数组则判断主键是否在此数组中) 
//                            startPid(第一层扫描的PID 默认0) currentDept(当前层 默认0)  maxDept(最大递归层 默认100) childKey(递归完成后子节点对应键 默认list) deptPrefix(根据层级重复的前缀 默认'')
                                parentKey: 'pId', //父级id对应键 
                                checkedKey: checked//节点是否选中的字段 默认checked
//                                ,openchecked:true
                            });
                            authtree.render('#LAY-auth-tree-index', trees, {
//                                inputname: 'rightIds[]', //上传上去的input表单的名字 默认meudis[]
                                layfilter: 'lay-check-auth', //input元素的lay-filter
                                autowidth: true
                            });
                            authtree.closeDept('#LAY-auth-tree-index', 2); //只显示到第二层
//                            authtree.checkAll('#LAY-auth-tree-index');
                        }
                    });
                }

                $('#search_role_name').click(function () {
                    search();
                });
                $('#role_name').on('keypress', function (event) {
                    if (event.keyCode == 13) {//键盘回车事件
                        search();
                    }
                });
//               监听select选择
                form.on('select()', function () {
                    search();
                });
//                搜索
                function search() {
                    tableIns.reload({
                        where: {
                            name: $('#role_name').val(),
                            status: $('#role_status').val()
                        }
                    });
                }

//                重置搜索条件
                $('#reset').click(function () {
                    $('#role_name').val('');
//                    $('#role_status').val('');
                    form.val('*', {
//                        'role_name': '',
                        'role_status': ''
                    });
                    tableIns.reload({where: {}});
                });
            });
            $(document).ajaxError(new jQueryAjaxErrorHandler());
        </script>
    </body>
</html>
